﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Common;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.IO;

namespace MetaData
{
    public class WindowScraper
    {
        MetaDataBag dataBag;
        AppWindow tableWindow;
        public Bitmap CurrentFrame { get; set; }
        public WindowScraper(MetaDataBag bag)
        {
            dataBag = bag;
            tableWindow = FindTable();
            tableWindow.Location = new Point(0, 0);
            tableWindow.BringWindowToFront();
            System.Threading.Thread.Sleep(1000);
            CaptureWindow();
        }




        int GetRegionSignature(int bgColor)
        {
            return GetRegionSignature(new Rectangle(new Point(0,0),CurrentFrame.Size), bgColor);
        }
        public int GetRegionSignature(Rectangle rect,int bgColor)
        {
            return GetRegionSignature(CurrentFrame,rect, bgColor);
        }
        [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern int memcmp(byte[] b1, byte[] b2, UIntPtr count);

        public byte[] GetRegionData(Rectangle rect)
        {
            BitmapData bData = CurrentFrame.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            int arrayLength = rect.Height * rect.Width * 4;
            byte[] array = new byte[arrayLength];
            Marshal.Copy(bData.Scan0, array, 0, arrayLength);
            CurrentFrame.UnlockBits(bData);
            return array;

        }
         public Bitmap GetRegion(Rectangle section)
        {
            Bitmap bmp = new Bitmap(section.Width, section.Height);
            Graphics g = Graphics.FromImage(bmp);

            g.DrawImage(CurrentFrame, 0, 0, section, GraphicsUnit.Pixel);

            // Clean up
            g.Dispose();

            // Return the bitmap
            return bmp;
        }
        bool SequenceEqual(byte[] b1, byte[] b2)
        {

            if (b1 == b2) return true; //reference equality check
            if (b1 == null || b2 == null || b1.Length != b2.Length) return false;
            return memcmp(b1, b2, new UIntPtr((uint)b1.Length)) == 0;
        }
    }
}
